package cn.tedu.vrd07.controller;

import cn.tedu.vrd07.entity.User;
import cn.tedu.vrd07.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;

    @RequestMapping("/login")
    public int login(User user, String rem, HttpSession session, HttpServletResponse response){
        User u = mapper.check(user.getUsername());
        if(u!=null){
            if(user.getPassword().equals(u.getPassword())){
                if(rem!=null){
                    Cookie c1 = new Cookie("username",user.getUsername());
                    c1.setMaxAge(60*60*24*30);
                    Cookie c2 = new Cookie("password",user.getPassword());

                    response.addCookie(c1);
                    response.addCookie(c2);
                }
                session.setAttribute("user",u);
                return 1;//登录成功!
            }else{
                return 3;
            }
        }
        return 2;
    }

    @RequestMapping("checkLogin")
    public User checkLogin(HttpSession session){
        //把登录成功时保存的用户对象返回给客户端
        return (User) session.getAttribute("user");
    }

    @RequestMapping("/logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }
}
